package lumis.service.tag;

import javax.persistence.NoResultException;

import lumis.doui.processaction.ProcessActionHandler;
import lumis.portal.PortalException;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.serviceinstance.ServiceInstanceConfig;
import lumis.portal.serviceinstance.ServiceInstanceDependencyConfig;
import lumis.portal.serviceinterfaceinstance.ServiceInterfaceInstanceConfig;
import lumis.util.PortalUtil;

/**
 * The process action to perform the tag repository selection.
 * 
 *
 * @version $Revision: 13092 $ $Date: 2011-05-28 18:19:06 -0300 (Sat, 28 May 2011) $
 * @since 6.0.0
 */
public class SelectRepositoryProcessActionHandler extends ProcessActionHandler
{
	public void processAction() throws PortalException
	{
		String serviceInterfaceInstanceId = douiContext.getRequest().getCallerServiceInterfaceInstanceId();
		ServiceInterfaceInstanceConfig callerInterfaceInstanceConfig = ManagerFactory.getServiceInterfaceInstanceManager().get(sessionConfig, serviceInterfaceInstanceId, transaction);

		String serviceInstanceId = douiContext.getRequest().getParameter("serviceInstanceId");
		if (serviceInstanceId != null)
		{
			// check if the service instance is an image service instance
			ServiceInstanceConfig serviceInstanceConfig = ManagerFactory.getServiceInstanceManager().get(serviceInstanceId, transaction);
			if (!"lumis.service.tag".equals(serviceInstanceConfig.getServiceId()))
			{
				throw new PortalException("STR_MAY_SELECT_ONLY_TAG_SERVICE_INSTANCE", getResource());
			}
		}
		
		try
		{
			// previous tag service instance association exists! 
			String tagServiceInstanceId = (String)ManagerFactory.getEntityManager().createQuery(
				"select distinct ts.serviceInstanceId from ContentLocale cl inner join cl.tags ts where cl.content.serviceInstanceId = :serviceInstanceId")
				.setParameter("serviceInstanceId", callerInterfaceInstanceConfig.getServiceInstanceId())
				.getSingleResult();
							
			if(!tagServiceInstanceId.equals(serviceInstanceId))
				throw new PortalException("STR_CHANGE_TAG_REPOSITORY_WHEN_TAGS_ARE_BEING_USED_IS_NOT_ALLOWED", getResource());
		}
		catch (NoResultException e) 
		{
			// no tag associated from other service instance, allow association.
		}

		ServiceInstanceDependencyConfig dependencyConfig = new ServiceInstanceDependencyConfig();
		dependencyConfig.setId(PortalUtil.generateNewGuid());
		dependencyConfig.setServiceInstanceId(serviceInstanceId);
		dependencyConfig.setDependentServiceInstanceId(callerInterfaceInstanceConfig.getServiceInstanceId());
		dependencyConfig.setDependencyType(ServiceInstanceDependencyConfig.DEPENDENCY_TYPE_TAG_REPOSITORY);			
		ManagerFactory.getServiceInstanceManager().setServiceInstanceDependency(dependencyConfig, transaction);
		
		addDefaultResponse();
	}
}

